package com.andersen.web.controller;

import com.andersen.database.entity.EmployeeEntity;
import com.andersen.database.entity.OfficeEntity;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Avseenko Dmitrij
 * Date: 25.03.14
 * Time: 9:49
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class EditOfficeController extends AbstractController{

    @RequestMapping(value = "/editOffice", method = RequestMethod.POST)
    public String openEditComponentsPagePOST (HttpServletRequest req, HttpServletResponse response){
        return "editOffice";
    }

    @RequestMapping(value = "/editOffice", method = RequestMethod.GET)
    public String openEditComponentsPageGET (ModelMap map){
        return "editOffice";
    }

    // Возвращаем список офисов
    @RequestMapping(value = "/getOffice", method = RequestMethod.POST)
    public @ResponseBody JSONObject getOffice (HttpServletRequest req, HttpServletResponse response){

        List<OfficeEntity>listOffice =  officeService.getOfficeList();

        JSONArray arrayJson = new JSONArray();

        for(OfficeEntity entity : listOffice){

            JSONObject jsonObject = new JSONObject();

            jsonObject.accumulate("id",entity.getId());
            jsonObject.accumulate("name",entity.getName());
            jsonObject.accumulate("location",entity.getLocation());
            jsonObject.accumulate("address",entity.getAddress());
            jsonObject.accumulate("manager",officeService.getFIOManager( entity.getManagerId()) );

            arrayJson.add(jsonObject);
        }

        JSONObject ret = new JSONObject();
        ret.accumulate("aaData",arrayJson);
        long tableSize = listOffice.size();
        ret.accumulate("iTotalRecords", String.valueOf(tableSize));
        ret.accumulate("iTotalDisplayRecords", String.valueOf(tableSize));

        return ret;
    }

    // возвращаем список менеджеров (ФИО одной строкой)
    @RequestMapping(value = "/getManagers", method = RequestMethod.POST)
    public @ResponseBody JSONObject getManagers (HttpServletRequest req, HttpServletResponse response){


        ArrayList<EmployeeEntity>listManager = new ArrayList(employeeService.getManagerList());

        long officeId =  Long.parseLong(req.getParameter("id"));

        // если нужна сортировка (выпадающее меню при редактировании)
        if(officeId != -1){

            long managerId = officeService.getIdManager(officeId);

            int index;
            for (EmployeeEntity entity : listManager){
                if(entity.getId() == managerId){
                    index = listManager.indexOf(entity);

                    EmployeeEntity entityBuf;

                    entityBuf = listManager.get(0);
                    listManager.set(0,entity);
                    listManager.set(index,entityBuf);
                    break;
                }
            }
        }

        JSONArray arrayJson = new JSONArray();

        for(EmployeeEntity entity : listManager){

            JSONObject jsonObject = new JSONObject();

            jsonObject.accumulate("id",entity.getId());
            jsonObject.accumulate("name",entity.getName());
            arrayJson.add(jsonObject);
        }

        JSONObject ret = new JSONObject();
        ret.accumulate("values",arrayJson);

        return ret;
    }


    // Добавляем офис
    @RequestMapping(value = "/addOffice", method = RequestMethod.POST)
    public void addOffice (HttpServletRequest req, HttpServletResponse response){

        String newName = req.getParameter("newNameOffice");
        String newLocation = req.getParameter("newLocationOffice");
        String newAddress = req.getParameter("newAddressOffice");
        long newManagerId = Long.valueOf(req.getParameter("newManagerOfficeId")).longValue();

        officeService.addOffice(newName,newLocation,newAddress,newManagerId);
    }

    // Редактирование офиса
    @RequestMapping(value = "/editOfficeInf", method = RequestMethod.POST)
    public void editOfficeInf (HttpServletRequest req, HttpServletResponse response){


        long id = Long.valueOf(req.getParameter("id")).longValue();
        String newName = req.getParameter("newNameOffice");
        String newLocation = req.getParameter("newLocationOffice");
        String newAddress = req.getParameter("newAddressOffice");
        long newManagerId = Long.valueOf(req.getParameter("newManagerOfficeId")).longValue();

        officeService.editOffice(id,newName,newLocation,newAddress,newManagerId);
    }

    // Удаление офиса
    @RequestMapping(value = "/removeOffice", method = RequestMethod.POST)
    public void removeOffice (HttpServletRequest req, HttpServletResponse response){

        long id = Long.valueOf(req.getParameter("id")).longValue();
        officeService.removeOffice(id);
    }

}


